<template>
  <div class="app-container">
    <div>
      <el-form>
        <el-form-item>
          <el-button type="success" icon="plus" v-if="hasPerm('task:add')" @click="showCreate">添加任务</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table
      :data="list"
      v-loading.body="listLoading"
      element-loading-text="拼命加载中"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="序号" prop="id" width="80"></el-table-column>
      <el-table-column align="center" label="cron表达式" prop="cronExpression" width="150"></el-table-column>
      <el-table-column align="center" label="任务组" prop="jobGroup" width="150"></el-table-column>
      <el-table-column align="center" label="任务中文名" prop="jobNameLabel" width="150"></el-table-column>
      <el-table-column align="center" label="任务名" prop="jobName" width="150"></el-table-column>
      <el-table-column align="center" label="完整类名" prop="beanClass" width="350"></el-table-column>
      <el-table-column align="center" label="描述" prop="description" width="150"></el-table-column>
      <el-table-column align="center" label="任务状态" prop="jobStatus" width="100">
        <template slot-scope="scope">
          <div v-if="scope.row.jobStatus == '1'">
            <span>运行中</span>
          </div>
          <div v-if="scope.row.jobStatus == '0'">
            <span>暂停</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column align="center" label="创建时间" prop="createDate" width="200"></el-table-column>
      <el-table-column align="center" label="更新时间" prop="updateDate" width="200"></el-table-column>
      <el-table-column align="center" label="创建者" prop="createBy"></el-table-column>
      <!-- <el-table-column align="center" label="昵称">
        <template slot-scope="scope">
          <div v-for="user in scope.row.users" v-bind:key="user.userId"> 
            <div v-text="user.nickname" style="display: inline-block;vertical-align: middle;"></div>
          </div>
        </template>
      </el-table-column>-->

      <el-table-column align="center" label="管理" fixed="right" width="300">
        <template slot-scope="scope">
          <div v-if="scope.row.roleName != '超级管理员'">
            <el-button
              type="primary"
              icon="edit"
              @click="changeStatus(scope.row.id, '0')"
              v-if="scope.row.jobStatus == '0'"
            >启动</el-button>
            <el-button
              v-if="scope.row.jobStatus == '1'"
              type="danger"
              icon="delete"
              @click="changeStatus(scope.row.id, '1')"
            >停止</el-button>
            <el-button
              type="primary"
              icon="edit"
              @click="showUpdate(scope.row)"
              v-if="hasPerm('task:edit')"
            >修改</el-button>
            <el-button
              v-if="hasPerm('task:delete')"
              type="danger"
              icon="delete"
              @click="removeTask(scope.row.id)"
            >删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        class="small-space"
        :model="taskform"
        label-position="left"
        label-width="100px"
        style="width: 1000px; margin-left:50px;"
        ref="taskform"
        :rules="taskformRules"
      >
        <el-form-item label="任务名称" prop="jobName">
          <el-select
            v-model="taskform.jobName"
            placeholder="请选择"
            :disabled="isdisabled"
            @change="onSelectedDrug"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="时间表达式" label-width="120px" style="width:35%">
          <el-input
            v-model="taskform.cronExpression"
            auto-complete="off"
          ></el-input>
        </el-form-item>-->
        <el-row>
          <el-col :span="8">
            <el-form-item label="定时策略" prop="cronExpression">
              <el-input v-model="taskform.cronExpression" placeholder="请输入定时策略" readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <el-button type="primary" @click="showCronDialog">生成 cron</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="success" @click="createTask(rowid)">保存</el-button>
      </div>
    </el-dialog>
    <el-dialog title="生成 cron" :visible.sync="showCron">
      <vcrontab @hide="showCron = false" @fill="crontabFill" :expression="expression"></vcrontab>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      list: [], //表格的数据
      allPermission: [],
      listLoading: false, //数据加载等待动画
      dialogStatus: "create",
      dialogFormVisible: false,
      showCron: false,
      isdisabled: false,
      expression: "",
      rowid: "",
      taskform: {
        cronExpression: "",
        jobName: "",
        jobNameLabel: ""
      },
      taskformRules: {
        jobName: [
          { required: true, message: "请输入任务名称", trigger: "change" }
        ],
        cronExpression: [
          { required: true, message: "请输入cron表达式", trigger: "blur" }
        ]
      },
      textMap: {
        update: "编辑任务",
        create: "新建任务"
      },
      options: [
        {
          value: "todayJobUserOrder",
          label: "每日订单下单数任务"
        },
        {
          value: "todayJobUser",
          label: "每日下单人数任务"
        }
      ],
      adminName: "超级管理员"
    };
  },
  created() {
    this.getList();
  },
  methods: {
    showCronDialog() {
      this.expression = this.taskform.cronExpression; //传入的 cron 表达式，可以反解析到 UI 上
      this.showCron = true;
    },
    crontabFill(val) {
      this.taskform.cronExpression = val;
    },
    getList() {
      //查询列表
      this.listLoading = true;
      this.api({
        url: "/sys-task/list",
        method: "get"
      }).then(data => {
        this.listLoading = false;
        this.list = data;
      });
    },
    changeStatus(id, status) {
      //改变定时任务状态status 1:运行 2:停止
      this.listLoading = true;
      let params = new FormData();
      params.append("jobId", id);
      params.append("cmd", status);
      this.api({
        url: "/sys-task/changeStatus",
        method: "post",
        data: params
      }).then(data => {
        this.listLoading = false;
        this.getList();
      });
    },

    showCreate() {
      this.dialogFormVisible = true;
      this.dialogStatus = "create";
      this.isdisabled = false;
      this.rowid = "";
      this.taskform.jobName = "";
      this.taskform.cronExpression = "";
    },
    showUpdate(row) {
      this.rowid = "";
      this.dialogFormVisible = true;
      this.dialogStatus = "update";
      const index = this.options.findIndex(
        option => option.value === row.jobName
      );
      this.taskform.jobName = this.options[index].label;
      this.taskform.cronExpression = row.cronExpression;
      this.isdisabled = true;
      this.rowid = row.id;
    },
    onSelectedDrug(val) {
      let obj = {};
      obj = this.options.find(item => {
        return item.value === val;
      });
      this.taskform.jobNameLabel = obj.label;
    },
    createTask() {
      let params = new FormData();
      let url = "";
      if (this.rowid == "") {
        url = "/sys-task/addjob";
        params.append("jobName", this.taskform.jobName);
        params.append("jobNameLabel", this.taskform.jobNameLabel);
      } else {
        url = "/sys-task/updateCron";
      }
      params.append("cronExpression", this.taskform.cronExpression);
      params.append("jobid", this.rowid);
      this.$refs["taskform"].validate(valid => {
        if (valid) {
          this.api({
            url: url,
            method: "post",
            data: params
          }).then(data => {
            this.listLoading = false;
            this.getList();
            this.dialogFormVisible = false;
          });
        } else {
          return false;
        }
      });
    },
    updateTask() {},
    removeTask(id) {
      let _vue = this;
      this.$confirm("确定删除此任务?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let params = new FormData();
        params.append("id", id);
        _vue
          .api({
            url: "/sys-task/deljob",
            method: "post",
            data: params
          })
          .then(() => {
            _vue.getList();
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });
      });
    }
  }
};
</script>
<style scoped>
.requiredPerm {
  color: #ff0e13;
}
.el-form-item .el-button {
  width: 100px;
  height: 40px;
  margin-left: 0;
}
.el-checkbox + .el-checkbox {
  margin-left: 0;
}
</style>
